//
//  XuanZeLianXiRenViewController.m
//  faYunTong
//
//  Created by iMac on 2023/6/15.
//  Copyright © 2023 iningKe. All rights reserved.
//

#import "XuanZeLianXiRenViewController.h"
#import "XuanZeLianXiRenTableViewCell.h"
#import "BMChineseSort.h"
@interface XuanZeLianXiRenViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,DZNEmptyDataSetDelegate,DZNEmptyDataSetSource>{
    NSMutableArray *dataSource;
    NSArray *orignArray;
    NSMutableArray *selectedArray;
}
@property (weak, nonatomic) IBOutlet UITextField *searchTf;
@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingTableView *mainTableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSpace;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;


//排序后的出现过的拼音首字母数组
@property(nonatomic,strong)NSMutableArray *indexArray;
//排序好的结果数组
@property(nonatomic,strong)NSMutableArray *letterResultArr;

@end

@implementation XuanZeLianXiRenViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    self.navTitleString = @"关联客户";
    
    self.topSpace.constant = NavaBarHeight;
    
    
    self.bottomSpace.constant = 20+ScreenBottom;
    
    [self.mainTableView registerNib:[UINib nibWithNibName:@"XuanZeLianXiRenTableViewCell" bundle:nil] forCellReuseIdentifier:@"XuanZeLianXiRenTableViewCell"];
 

    if (@available(iOS 11.0, *)) {
        self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    if (@available(iOS 15.0, *)) {
        self.mainTableView.sectionHeaderTopPadding = 0 ;
    } else {
        // Fallback on earlier versions
    }
    
    self.indexArray = [NSMutableArray array];
    self.letterResultArr = [NSMutableArray array];
    
    self.mainTableView.sectionIndexColor = rgba(153, 153, 153, 1);
    selectedArray = [NSMutableArray array];
    
    if(_manageType == 2){
        dataSource = [NSMutableArray array];
        for (NSDictionary *dataDic in _dataArray) {
            AllModel *model = [[AllModel alloc] init];
            model.avatar = GetHandleString(dataDic, @"avatar");
            model.idString = GetHandleString(dataDic, @"imUserId");
            model.name = GetHandleString(dataDic, @"name");
            model.deptName = GetHandleString(dataDic, @"deptName");
            [dataSource addObject:model];
        }
        [self sortByArray:dataSource];
        
        self.navTitleString = @"移除联系人";
    }else if(_manageType == 1){
        [self getgroupChatInfoFromServer];
    }else{
        [self getInfoFromServer];
    }
}
- (IBAction)souSuo:(UITapGestureRecognizer *)sender {
    [self.view endEditing:YES];
    if(_searchTf.text.length == 0){
        [self sortByArray:dataSource];
    }else{
        NSMutableArray *arry = [NSMutableArray array];
        for (AllModel *model in dataSource) {
            if([model.name containsString:_searchTf.text]){
                [arry addObject:model];
            }
        }
        [self sortByArray:arry];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    if(textField.text.length == 0){
        [self sortByArray:dataSource];
    }else{
        NSMutableArray *arry = [NSMutableArray array];
        for (AllModel *model in dataSource) {
            if([model.name containsString:textField.text]){
                [arry addObject:model];
            }
        }
        [self sortByArray:arry];
    }
    return YES;
}


- (void)getInfoFromServer{
    [[ZZPRequest getWebUtil] getNetworkRequestURLString:[NSString stringWithFormat:@"/app/groupChat/employee?nickName=%@",@""] andParas:nil andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            orignArray = [info objectForKey:@"rows"];
            dataSource = [NSMutableArray array];
    
            for (NSDictionary *dataDic in orignArray) {
                AllModel *model = [[AllModel alloc] init];
                model.avatar = GetHandleString(dataDic, @"avatar");
                model.idString = GetHandleString(dataDic, @"id");
                model.name = GetHandleString(dataDic, @"nickName");
                model.deptName = GetHandleString(dataDic, @"deptName");
                [dataSource addObject:model];
            }
    
            [self sortByArray:dataSource];
     
        }
    }];
}

//查询群聊可添加用户
- (void)getgroupChatInfoFromServer{
    [[ZZPRequest getWebUtil] getNetworkRequestURLString:[NSString stringWithFormat:@"/app/groupChat/add?groupId=%@",_groupId] andParas:nil andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            orignArray = [info objectForKey:@"rows"];
            dataSource = [NSMutableArray array];
    
            for (NSDictionary *dataDic in orignArray) {
                AllModel *model = [[AllModel alloc] init];
                model.avatar = GetHandleString(dataDic, @"avatar");
                model.idString = GetHandleString(dataDic, @"id");
                model.name = GetHandleString(dataDic, @"nickName");
                model.deptName = GetHandleString(dataDic, @"deptName");
                [dataSource addObject:model];
            }
            [self sortByArray:dataSource];
        }
    }];
}



- (BOOL)isHaveSelected:(NSString *)idString{
    BOOL isSelected = NO;
    for (NSDictionary *dataDic in _dataArray) {
        if([idString isEqualToString:GetHandleString(dataDic, @"userId")]){
            isSelected = YES;
            break;
        }
    }
    return isSelected;
}


- (void)sortByArray:(NSArray *)array{
    BMChineseSortSetting.share.sortMode = 1; // 1或2
    BMChineseSortSetting.share.specialCharPositionIsFront = NO;
    //排序 Person对象
    [BMChineseSort sortAndGroup:array key:@"name" finish:^(bool isSuccess, NSMutableArray *unGroupArr, NSMutableArray *sectionTitleArr, NSMutableArray<NSMutableArray *> *sortedObjArr) {
        if (isSuccess) {
            self.indexArray = [NSMutableArray arrayWithArray:sectionTitleArr];
            self.letterResultArr = [NSMutableArray arrayWithArray:sortedObjArr];
            [_mainTableView reloadData];
        }
    }];
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return [self.indexArray count];
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(nonnull UIView *)view forSection:(NSInteger)section {
    view.tintColor = [UIColor whiteColor];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 34;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    return [self.indexArray objectAtIndex:section];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.letterResultArr objectAtIndex:section] count];
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    
    return self.indexArray;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    return index;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    XuanZeLianXiRenTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XuanZeLianXiRenTableViewCell"];
    AllModel *model = [[self.letterResultArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    [cell.headImage sd_setImageWithURL:WebImagePath(model.avatar) placeholderImage:LocalImagePath(@"默认头像")];
    cell.selectButton.selected = [selectedArray containsObject:model];
    cell.nameLabel.text = model.name;
    cell.buMenLabel.text = model.deptName;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 69;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.view endEditing:YES];
    [self.view endEditing:YES];
    
    AllModel *model = [[self.letterResultArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];

    if([selectedArray containsObject:model]){
        [selectedArray removeObject:model];
    }else{
        [selectedArray addObject:model];
    }
    

    
}





-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return selectedArray.count;
}


//完成
- (IBAction)wanCheng:(UIButton *)sender {
    
    
    if(selectedArray.count == 0){
        [ZZPUtils showWarning:@"请先选择用户"];
        return;
    }
    
    if(_manageType == 1){
        //添加
        NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
        [paraDic setValue:_groupId forKey:@"id"];
        NSMutableArray *array = [NSMutableArray array];
        for (AllModel *model in selectedArray) {
            NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
            [dataDic setValue:model.idString forKey:@"userId"];
            [array addObject:dataDic];
        }
        [paraDic setValue:array forKey:@"groupChatMemberList"];
        [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/app/groupChat/member" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
            if(!error){

                [ZZPUtils showWarning:@"添加成功"];
                
                if(_manageResult){
                    _manageResult();
                }
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
        
        return;
    }
    if(_manageType == 2){
        //移除

        NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
        [paraDic setValue:_groupId forKey:@"id"];
        NSMutableArray *array = [NSMutableArray array];
        for (AllModel *model in selectedArray) {
            NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
            [dataDic setValue:model.idString forKey:@"imUserId"];
            [array addObject:dataDic];
        }
        [paraDic setValue:array forKey:@"groupChatMemberList"];
        [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/app/groupChat/member/delete" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
            if(!error){

                [ZZPUtils showWarning:@"移除成功"];
                
                if(_manageResult){
                    _manageResult();
                }
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
        
        return;
    }

    
}


//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView{
//    return -90;
//}

-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"暂无数据"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {

        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"暂无联系人~"attributes: @{NSFontAttributeName: [UIFont systemFontOfSize:16],NSForegroundColorAttributeName:rgba(130, 137, 168, 1)}];
        return string;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return YES;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
